'use strict';

const Service = require('egg').Service;
const Mock = require('mockjs');

class OrderService extends Service {
    async getList() {
        const {
            ctx,
            app
        } = this;
        // const {
        //     list
        // } = Mock.mock({
        //     "list|10": [{
        //         name: "@cname", //用户名
        //         tel:/[1][3-8]\d{9}/,//电话
        //         "type|1":['二手房出租','有房出租','我想买个房','我想租个房'],
        //         money:10,//支付金额
        //         pay_time: Date.now(), //支付时间
        //     }]
        // });
        // list.forEach((item) => {
        //     app.mysql.insert('orders', {
        //         ...item
        //     })
        // })
        // return '123'
        const {
            pageSize,
            pageIndex,
            type,
            keyword
        } = ctx.query;
        let sql = `select * from orders where 1=1 `;
        let sqlCount = `select count(id) as total from orders where 1=1 `;
        // 类型
        if(type) {
            sql += `and type = '${type}' `
            sqlCount += `and type = '${type}' `
        }
        // 多字段查询
        if(keyword) {
            sql += `and concat(name,tel) like '%${keyword}%'`
            sqlCount += `and concat(name,tel) like '%${keyword}%'`
        }
        //分页
        if (pageSize && pageIndex) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        let res = await app.mysql.query(sql);
        let [{
            total
        }] = await app.mysql.query(sqlCount);
        res.forEach((item, index) => {
            // 序号
            item.number = (pageIndex - 1) * 5 + index + 1;
        })
        return {
            data: res,
            total: total
        }
    }
    // 删除订单
    async delOrder() {
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.request.body;
        let res = await app.mysql.delete('orders', {
            id
        });
        return res
    }
}

module.exports = OrderService;